package org.lc.service.system.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.lc.platform.mybatis.crud.service.impl.CrudBaseServiceImpl;
import org.lc.platform.mybatis.manager.query.QueryBuilder;
import org.lc.service.system.dto.SysDepartmentDto;
import org.lc.service.system.entity.SysDepartment;
import org.lc.service.system.entity.SysDepartmentRole;
import org.lc.service.system.entity.SysRole;
import org.lc.service.system.mapper.SysDepartmentMapper;
import org.lc.service.system.service.SysDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SysDepartmentServiceImpl extends CrudBaseServiceImpl<SysDepartmentDto, SysDepartment, SysDepartmentMapper, SysDepartment> implements SysDepartmentService {

    @Override
    public SysDepartment Convertor(SysDepartment data) {
        return data;
    }

    @Override
    public QueryBuilder<SysDepartment> getQueryBuilder(SysDepartmentDto query, QueryBuilder<SysDepartment> queryBuilder) {
        if ("noParent".equals(query.getParentId())) {
            queryBuilder.isNull("parent_id");
        } else {
            queryBuilder.eq(query.getParentId() != null, "parent_id", query.getParentId());
            queryBuilder.relation(SysDepartment.class);
        }
        queryBuilder.relation(SysRole.class);
        queryBuilder.like(query.getTitle() != null, "title", query.getTitle());
        return queryBuilder;
    }

    @Override
    @Transactional
    public Boolean createBaseOne(SysDepartment body) {
        super.createBaseOne(body);
        saveRoles(body.getId(), body.getRoles());
        return true;
    }

    @Override
    @Transactional
    public Boolean updateBaseOne(String id, SysDepartment data) {
        saveRoles(id, data.getRoles());
        return super.updateBaseOne(id, data);
    }

    private void saveRoles(String departmentId, List<SysRole> roleIds) {
        var warp = Db.lambdaQuery(SysDepartmentRole.class).getWrapper();
        warp.eq(SysDepartmentRole::getSysDepartmentId, departmentId);
        var count = Db.count(warp);
        if (count > 0) {
            Db.remove(warp);
        }
        if (roleIds != null) {
            List<SysDepartmentRole> data = roleIds.stream().map(r -> new SysDepartmentRole(r.getId(), departmentId)).toList();
            Db.saveBatch(data);
        }
    }

    @Override
    public List<SysDepartment> getDepartmentTreeList() {
        return this.manager.createQueryBuilder().isNull("parent_id").selectTreeLevel();
    }
}